package cameracontrol;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.HashMap;

import se.lth.cs.cameraproxy.Axis211A;
import se.lth.cs.realtime.JThread;
import se.lth.cs.realtime.RTThread;
import survey.Synchronizer;
import util.Picture;

/**
 * DatagramPictureCollector is a Thread which recevies pictures through a UDP/IP
 * socket connected to CameraServer. The pictures recevied are in raw byte code
 * and are converted to a Class Picture. The pictures are sent to
 * SurveyController through a mailbox.
 */
public class DatagramPictureCollector extends Thread {
	private Synchronizer sc;
	private DatagramSocket socket;
	private boolean run = true;

	/**
	 * Constructs the class and starts a socket.
	 * 
	 * @param port
	 *            - the port which the client listens to
	 * @param sc
	 *            - the class SurveyController
	 */
	public DatagramPictureCollector(int port, Synchronizer sc) {
		this.sc = sc;
		try {
			this.socket = new DatagramSocket(port);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Called when the thread is started. Receives byte arrays and converts
	 * these to Pictures then sends the pictures to the SurveyController.
	 */
	@Override
	public void run() {
		DatagramPacket packet;		
		while (run) {
			byte jpeg[] = new byte[Axis211A.IMAGE_BUFFER_SIZE];
			packet = new DatagramPacket(jpeg, jpeg.length);
			try {
				socket.receive(packet);
			} catch (IOException e) {
				continue;
			}
			InetSocketAddress addr = (InetSocketAddress) packet
					.getSocketAddress();
			Picture p = new Picture(jpeg, addr);
			if (500 > p.getDelay()) {
				p.setSync(true);
			} else {
				p.setSync(false);
			}
			sc.insertPicture(p);
		}

	}

	public void kill() {
		this.run = false;
		socket.close();
		try {
			this.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
